import logging
from typing import List

from fastapi import APIRouter, Depends, HTTPException, Body

from app.admin.schemas.user import User, UserCreate, UserUpdate
from app.admin.services.user_service import user_service
from app.admin.services.tenant_service import tenant_service
from app.schemas.token import APIResponse
from app.security.auth import (
    get_current_active_user,
    get_current_active_superuser,
    PermissionRequired,
)

# 配置日志
logger = logging.getLogger(__name__)

router = APIRouter()


@router.post("", response_model=APIResponse[User])
async def create_user(
    user: UserCreate,
    tenant_id: str = None,
    current_user: User = Depends(get_current_active_superuser),
):
    """
    创建新用户（仅限超级用户）
    """
    logger.debug(f"尝试创建用户，参数：{user}")
    if tenant_id is None:
        raise HTTPException(
            status_code=400,
            detail=APIResponse(code=400, msg=f"租户ID不能为空。", data=None),
        )
    if user.login_name is None:
        raise HTTPException(
            status_code=400,
            detail=APIResponse(code=400, msg=f"登录名不能为空。", data=None),
        )
    if user.full_name is None:
        raise HTTPException(
            status_code=400,
            detail=APIResponse(code=400, msg=f"姓名不能为空。", data=None),
        )
    if not await tenant_service.get_tenant(tenant_id=tenant_id):
        raise HTTPException(
            status_code=400,
            detail=APIResponse(code=400, msg=f"租户 [{tenant_id}] 不存在。", data=None),
        )
    
    if await user_service.check_login_name_exists(user.login_name):
        raise HTTPException(
            status_code=400,
            detail=APIResponse(
                code=400, msg=f"登录名 [{user.login_name}] 已存在", data=None
            ),
        )
    user.tenant_id = tenant_id
    created_user = await user_service.create_user(user=user)
    logger.info(f"创建用户成功。{created_user}")
    return APIResponse(code=200, msg="用户创建成功", data=created_user)


@router.get("", response_model=APIResponse[List[User]])
async def read_users(
    tenant_id: str = None,
    skip: int = 0,
    limit: int = 100,
    current_user: User = Depends(get_current_active_superuser),
):
    """
    获取用户列表（需要用户访问权限）
    如果未提供租户ID，则使用当前用户的租户ID
    """
    users = await user_service.get_users(skip=skip, limit=limit, tenant_id=tenant_id)
    return APIResponse(code=200, msg="获取用户列表成功", data=users)


@router.get("/{user_id}", response_model=APIResponse[User])
async def read_user(
    user_id: str,
    tenant_id: str = None,
    current_user: User = Depends(PermissionRequired("user_detail")),
):
    """
    根据ID获取用户信息（需要用户访问权限）
    """
    db_user = await user_service.get_user(user_id=user_id, tenant_id=tenant_id)
    if db_user is None:
        raise HTTPException(
            status_code=400,
            detail=APIResponse(code=400, msg=f"用户 [{user_id}] 不存在。", data=None),
        )
    return APIResponse(code=200, msg="获取用户信息成功", data=db_user)


@router.put("/{user_id}", response_model=APIResponse[User])
async def update_user(
    user_id: str,
    user_update: UserUpdate,
    tenant_id: str = None,
    current_user: User = Depends(get_current_active_user),
):
    """
    更新用户信息（需要登录）
    """
    if current_user.id != user_id and not current_user.is_superuser:
        raise HTTPException(status_code=403, detail="Not enough permissions")

    db_user = await user_service.update_user(user_id=user_id, user_update=user_update)
    if db_user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return APIResponse(code=200, msg="用户信息更新成功", data=db_user)


@router.delete("/{user_id}", response_model=APIResponse[bool])
async def delete_user(
    user_id: str,
    tenant_id: str = None,
    current_user: User = Depends(get_current_active_superuser),
):
    """
    删除用户（仅限超级用户）
    """
    # 检查用户是否存在
    db_user = await user_service.get_user(user_id=user_id, tenant_id=tenant_id)
    if db_user is None:
        raise HTTPException(status_code=404, detail="User not found")

    # 不能删除自己
    if current_user.id == user_id:
        raise HTTPException(status_code=400, detail="Cannot delete yourself")

    success = await user_service.delete_user(user_id=user_id, tenant_id=tenant_id)
    return APIResponse(code=200, msg="用户删除成功", data=success)


@router.post("/{user_id}/roles", response_model=APIResponse[bool])
async def set_user_roles(
    user_id: str,
    role_ids: List[str] = Body(..., embed=True),
    current_user: User = Depends(get_current_active_superuser),
):
    """
    为用户设置角色（仅限超级用户）
    会覆盖用户当前的所有角色
    """
    # 检查用户是否存在
    db_user = await user_service.get_user(user_id=user_id)
    if db_user is None:
        raise HTTPException(status_code=404, detail="用户不存在。")

    success = await user_service.set_user_roles(user_id=user_id, role_ids=role_ids)
    if not success:
        raise HTTPException(status_code=404, detail="用户不存在。")

    return APIResponse(code=200, msg="用户角色设置成功", data=True)


@router.post("/{user_id}/reset-password", response_model=APIResponse[dict])
async def admin_reset_password(
    user_id: str, current_user: User = Depends(get_current_active_superuser)
):
    """
    管理员重置用户密码为默认密码（仅限超级用户）
    """
    logger.info(f"管理员 {current_user.login_name} 尝试重置用户密码: {user_id}")

    # 检查用户是否存在
    db_user = await user_service.get_user(user_id=user_id)
    if db_user is None:
        logger.warning(f"管理员重置密码失败: 用户不存在 - {user_id}")
        raise HTTPException(status_code=404, detail="用户不存在")

    # 不能重置自己的密码
    if current_user.id == user_id:
        logger.warning(f"管理员尝试重置自己的密码: {user_id}")
        raise HTTPException(status_code=400, detail="不能重置自己的密码")

    success = await user_service.admin_reset_password(user_id=user_id)

    if success:
        logger.info(f"管理员重置密码成功: {user_id}")
        return APIResponse(
            code=200,
            msg="用户密码已重置为默认密码 'passwd123'，请通知用户首次登录后修改密码",
            data={"user_id": user_id, "default_password": "passwd123"},
        )
    else:
        logger.error(f"管理员重置密码失败: {user_id}")
        raise HTTPException(status_code=500, detail="密码重置失败")
